<?php
namespace Modules\AuthAdmin\Models;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Modules\AuthAdmin\Services\AuthAdminService;
use Modules\AuthAdmin\Services\QueryService;
use Modules\AuthAdmin\Models\BaseApiModel;
use Modules\AuthAdmin\Models\AuthGroup as AuthGroupModel;
use Modules\AuthAdmin\Models\AuthRule as AuthRuleModel;
class AuthAdmin extends Authenticatable implements JWTSubject
{	 
	use Notifiable;
	protected $guard = 'auth_admin';
	protected $hidden = [
		'password'
	];
	/**
     * @name  jwt标识 
     */
	public function getJWTIdentifier()
    {
        return $this->getKey();
    }
	/**
     * @name  jwt自定义声明 
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
	/**
     * @name  用户登录 
     */
	public function login($data){
		$BaseApiModel = new BaseApiModel();
		if (true == \Auth::guard('auth_admin')->attempt($data)) {
			$user_info = $this->where(['username'=>$data['username']])->select('id','username')->first();
			if($user_info){
				$user_info = $user_info->toArray();
				$user_info['password'] = $data['password'];
				$token = (new AuthAdminService())->set_token($user_info);
				if(count($token)){
					return $BaseApiModel->api_success([
						'msg'=>'登录成功！',
						'data'=>$token
					]);
				}
				return $BaseApiModel->api_error(['msg'=>'登录失败！']);
			}
		}
		return $BaseApiModel->api_error(['msg'=>'账号或密码错误！']);
	}
	
	/**	 
	 * @name  刷新	 
	 */
    public function refresh()
    {
		$token = (new AuthAdminService())->refresh();
        return (new BaseApiModel())->api_success(['data'=>$token]);
    }
	/**	 
	 * @name  退出登录
	 */
    public function logout()
    {
		(new AuthAdminService())->logout();
        return (new BaseApiModel())->api_success(['msg'=>'退出成功！']);
    }
	/**	 
	 * @name  获取左侧栏
	 */
    public function menu()
    {
		$user_info = (new AuthAdminService())->my();
		$AuthRuleModel = (new AuthRuleModel())->query()->select('id','href','name','icon','pid');
		if($user_info['id'] != 1){
			$admin_rules_str = AuthGroupModel::where('id',$user_info['group_id'])->value('rules');
			$admin_rules = explode('|',$admin_rules_str);
			if(count($admin_rules)){
				$AuthRuleModel = $AuthRuleModel->whereIn('id',$admin_rules);
				$auth_rule_arr = $AuthRuleModel->orderBy('sort','asc')->orderBy('id','asc')->get()->toArray();
			}else{
				$auth_rule_arr = [];
			}
		}else{
			$auth_rule_arr = $AuthRuleModel->orderBy('sort','asc')->orderBy('id','asc')->get()->toArray();
		}
		return (new BaseApiModel())->api_success(['data'=>[
			'menu_list'=>(new AuthRuleModel())->auth_rule_arr($auth_rule_arr),
			'username'=>$user_info['username']
		]]);
		
    }
	/**
     * @name   状态0和1修改为true或false
     * @param  int  $value
     * @return Boolean 
     */
    public function getStatusAttribute($value)
    {
        return $value==1?true:false;
    }
	/**
     * @name   更新时间为null时返回
     * @param  int  $value
     * @return Boolean 
     */
    public function getUpdatedAtAttribute($value)
    {
        return $value?$value:'';
    }
	/**
	 * @name  关联权限组表   多对一
	 */
	 public function auth_groups()
    {
        return $this->belongsTo('Modules\AuthAdmin\Models\AuthGroup','group_id','id');
    }
	/**
	 * @name  列表数据
	 * @param  data  array 搜索数据
	 * @return json 
	 */
    public function list_data($data){
		$model = $this->query();
		$model = (new QueryService())->query_condition($model,$data,'username');
		if (isset($params['group_id']) && $params['group_id'] > 0){
            $model = $model->where('group_id',$params['group_id']);
        }			
        $list = $model->with([
					'auth_groups'=>function($query){
							$query->select('id','name');  
					}
				])
				->orderBy('id','desc') 
				->paginate($data['pagesize'])
				->toArray(); 
		return (new BaseApiModel())->api_success(['data'=>[
			'list'=>$list['data'],
			'total'=>$list['total']
		]]);		
	}
	/**
	 * @name  调整状态
	 * @param id int 调整id
	 * @param data array 调整数据
	 * @param success_msg string 成功返回数据
	 * @param error_msg string 失败返回数据
	 * @return 返回json数据
	 */
	public function admin_status_update($id,$data,$success_msg = '调整成功！',$error_msg = '调整失败！'){
		$BaseApiModel = new BaseApiModel();
		if ($this->where('id',$id)->update($data)){
			return $BaseApiModel->api_success(['msg'=>$success_msg]);
        }else{
			return $BaseApiModel->api_error(['msg'=>$error_msg]);
		}
	} 
	/**
	 * @name  添加方法
	 * @param data array 添加数据
	 * @param success_msg string 成功返回数据
	 * @param error_msg string 失败返回数据
	 * @return 返回json数据
	 */
	public function admin_create($data,$success_msg = '添加成功！',$error_msg = '添加失败！'){
		$BaseApiModel = new BaseApiModel();
		$data['password'] = bcrypt($data['password']);
		$data['created_at'] = date('Y-m-d H:i:s');
		if ($this->insert($data)){
			return $BaseApiModel->api_success(['msg'=>$success_msg]);
        }else{
			return $BaseApiModel->api_error(['msg'=>$error_msg]);
		}
	} 
	/**
	 * @name  编辑方法
	 * @param id int 编辑id
	 * @param data array 编辑数据
	 * @param success_msg string 成功返回数据
	 * @param error_msg string 失败返回数据
	 * @return 返回json数据
	 */
	public function admin_update($id,$data,$success_msg = '编辑成功！',$error_msg = '编辑失败！'){
		$BaseApiModel = new BaseApiModel();
		$data['updated_at'] = date('Y-m-d H:i:s');
		if ($this->where('id',$id)->update($data)){
			return $BaseApiModel->api_success(['msg'=>$success_msg]);
        }else{
			return $BaseApiModel->api_error(['msg'=>$error_msg]);
		}
	} 
	/**
     * @name  用户登录 
     */
	public function upadte_pwd_view($data){
		$BaseApiModel = new BaseApiModel();
		$user_info = (new AuthAdminService())->my();
		if (true == \Auth::guard('auth_admin')->attempt(['username'=>$user_info['username'],'password'=>$data['y_password']])) {
			if($this->where('id',$user_info['id'])->update(['password'=>bcrypt($data['password'])])){
				return $BaseApiModel->api_success(['msg'=>'修改成功！']);
			}else{
				return $BaseApiModel->api_error(['msg'=>'修改失败！']);
			}
		}else{
			return $BaseApiModel->api_error(['msg'=>'原密码错误！']);
		}
	}
}
